﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Examples
{
    /// <summary>
    /// Downloads all files in all folders in document library to destination folder
    /// </summary>
    class DownloadDocumentLibraryHierarchy
    {
        public static void DoIt(string connectionString, string folder)
        {
            using (var connection = new Camelot.SharePointConnector.Data.SharePointConnection(connectionString))
            {
                connection.Open();

                var data = Camelot.SharePointIntegration.DocumentLibraryDataUtility.CreateDocumentLibraryData("Shared Documents", null, connection);

                foreach (var doc in data.Documents)
                {
                    // folder
                    if (doc.ContentType == "Folder")
                        if (!Directory.Exists(folder + doc.Url))
                            Directory.CreateDirectory(folder + doc.Url);

                    // document
                    if (doc.ContentType != "Folder")
                    {
                        // skip file if same last modified date
                        if (File.Exists(folder + doc.Url))
                            if (File.GetLastWriteTime(folder + doc.Url) == doc.Modified)
                                continue;

                        using (var command = new Camelot.SharePointConnector.Data.SharePointCommand(string.Format("CALL DOWNLOAD('{0}', '{1}')", "Shared Documents", doc.ProcedureUrl), connection))
                        {
                            byte[] fileBytes = (byte[])command.ExecuteScalar();
                            if (fileBytes != null && fileBytes.Length > 0)
                            {
                                File.WriteAllBytes(folder + doc.Url, fileBytes);
                                File.SetCreationTime(folder + doc.Url, doc.Created);
                                File.SetLastWriteTime(folder + doc.Url, doc.Modified);
                            }
                        }

                        Console.WriteLine("Downloaded: " + doc.Name);
                    }
                }
            }
        }
    }
}
